package com.gitee.ed.arithmetic.leetcode.answer.answer_1_100.answer_1_10;

import com.gitee.ed.arithmetic.leetcode.solution.solution_1_100.solution_1_10.Solution7;

/**
 * @author hongda.li
 */
public class Answer7 implements Solution7 {
    @Override
    public int reverse(int x) {
        if (x == 0) {
            return 0;
        }

        boolean positive = x > 0;
        StringBuilder reverse = new StringBuilder(String.valueOf(x)).reverse();
        if (!positive) {
            reverse.deleteCharAt(reverse.length() - 1);
        }
        for (int i = 0; i < reverse.length(); i++) {
            if (reverse.charAt(i) == '0') {
                reverse.deleteCharAt(i);
                i--;
            } else {
                break;
            }
        }

        long num = positive ? Long.parseLong(reverse.toString()) : -Long.parseLong(reverse.toString());
        return num > Integer.MAX_VALUE || num < Integer.MIN_VALUE ? 0 : (int) num;
    }
}
